import React, { useEffect, useState } from "react";
import dayjs from "dayjs";
import "./index.scss";

/** 倒计时 */
export const Countdown = ({ time }: { time: string }) => {
  const [text, setText] = useState("");
  useEffect(() => {
    const calculate = () => {
      const end = new Date(time);
      var start = new Date();
      let diff = +end - +start;
      if (diff < 0) {
        setText("已结束");
        clearInterval(timer);
        return;
      }
      diff /= 1000;

      const day = parseInt(`${diff / 60 / 60 / 24}`);
      const hour = parseInt(`${(diff / 60 / 60) % 24}`);
      const minute = parseInt(`${(diff / 60) % 60}`);
      const second = parseInt(`${diff % 60}`);
      let newText = "";
      if (day) {
        newText += day + "天";
      }
      if (hour || newText) {
        newText += hour + "时";
      }
      if (minute || newText) {
        newText += minute + "分";
      }
      newText += second + "秒";
      setText(newText);
    };
    const timer = setInterval(() => {
      calculate();
    }, 1000);
    calculate();
    return () => {
      clearInterval(timer);
    };
  }, []);
  return <span className="count-down-text text">{text}</span>;
};

/** 多久之前 */
export const farForm = (time: string) => {
  const from = new Date(time);
  const now = new Date();
  if (+now - +from < 60 * 1000) {
    return "1分钟前";
  }
  if (+now - +from < 60 * 60 * 1000) {
    return "1小时前";
  }
  return dayjs(from).format("YYYY/MM/DD");
};
